<template>
    <div class="page_container">
        <el-tabs v-model="activeName" @tab-click="tabChange">
            <el-tab-pane :label="`收件箱${tabsCount.INBOX > 0 ? `(${tabsCount.INBOX})` : ''}`" 
                name="0" :disabled="loading"></el-tab-pane>
            <el-tab-pane :label="`草稿箱${tabsCount.DFBOX > 0 ? `(${tabsCount.DFBOX})` : ''}`" 
                name="1" :disabled="loading"></el-tab-pane>
            <el-tab-pane :label="`已发送${tabsCount.SNBOX > 0 ? `(${tabsCount.SNBOX})` : ''}`" 
                name="2" :disabled="loading"></el-tab-pane>
            <el-tab-pane :label="`已删除${tabsCount.DEBOX > 0 ? `(${tabsCount.DEBOX})` : ''}`" 
                name="3" :disabled="loading"></el-tab-pane>
        </el-tabs>
        <DataTableBar :data="tableData" :columns="columns" :config="config"
            :total="total" :pages="pages" :loading="loading"
            @search="search" @reset="searchReset" @refresh="refresh"
            @currentChange="currentChange" @sizeChange="sizeChange"
            @addBefore="addBefore" @selectionChange="handleSelectionChange">

            <template v-slot:tableoper>
                <el-button type="warning" plain class="oper_button" @click="readItems" v-if="activeName == '0'">
                    <i class="icon-base icon-base-readed margin-right-sm"></i>批量已读
                </el-button>
                <el-button type="danger" plain class="oper_button" @click="removeItems" v-if="activeName < '3'">
                    <i class="icon-base icon-base-shanchu margin-right-sm"></i>删 除
                </el-button>
                <el-button plain class="oper_button" @click="recoverItems" v-if="activeName == '3'">
                    <i class="icon-base icon-base-qiehuangongsi margin-right-sm"></i>恢 复
                </el-button>
            </template>

            <template v-slot:sender="scope">
                <div class="flex">
                    <span v-if="activeName == '0'">
                        <i class="icon-base icon-base-emailopen margin-right-sm" style="color: #999;font-size: 18px;" v-if="scope.row.readFlg == 'Y'"></i>
                        <i class="icon-base icon-base-newemail margin-right-sm" style="color: #1890FF;font-size: 18px;" v-else></i>
                    </span>
                    <i class="icon-base icon-base-emailopen margin-right-sm" style="color: #999;font-size: 18px;" v-else></i>
                    <span>{{ scope.row.asMail ? scope.row.asMail.senderName : '-' }}</span>
                </div>
            </template>

            <template v-slot:title="scope">
                <el-button link type="primary" @click="checkDetail(scope.row)">{{ scope.row.asMail ? scope.row.asMail.title : '-' }}</el-button>
            </template>

            <template v-slot:sendTime="scope">
                <span>{{ formatDate.dateTimeAllFormat( scope.row.asMail ? scope.row.asMail.sendTime : '') }}</span>
            </template>

        </DataTableBar>
        <CreateEmail v-model:show="createEmailDrawerShow" :defaultValue="selectrow" :state="operState"
            @submit="edit" @save="edit" @temporarySave="temporarySave"></CreateEmail>
        <EmailDetail ref="emailDetailRef" v-model:show="emailDetailDrawerShow" :data="selectrow" 
            @remove="removeItems"  @reply="(emailInfo) => {replyEmail( emailInfo, false )}" 
            @forward="(emailInfo) => {replyEmail( emailInfo, true )}"
            @close="refresh"></EmailDetail>
        <ReplyMode v-model:show="replyEmailDrawerShow" :defaultValue="selectrow" :state="replyState"
            @submit="edit"></ReplyMode>
    </div>
</template>

<script setup>
    // 收件箱
    import { ref, onMounted } from "vue";
    import { emailPages, createEmail, editEmail, removeEmails, readEamils, recoverEmail, tabsStatistics } from "@/api/email.js"
    import { ElMessage } from 'element-plus'
    import { formatDate } from "@/utils/fomart"
    import DataTableBar from "@/components/DataComponents/DataTableBar.vue"
    import CreateEmail from "./components/CreateEmail.vue"
    import EmailDetail from "./components/EmailDetail.vue"
    import ReplyMode from "./components/ReplyMode.vue"
    const { proxy } = getCurrentInstance();
    const emailDetailRef = ref(null);
    const activeName = ref('0');
    const createEmailDrawerShow = ref(false);
    const emailDetailDrawerShow = ref(false);
    const replyEmailDrawerShow = ref(false);
    const mailStatus = ref('1');
    const userTypes = ref('1,2');
    const pages = ref({ page_current: 1, page_size: 10 });
    const total = ref(0);
    const loading = ref(false);
    const searchParams = ref({});
    const selectedRows = ref([]);
    const selectrow = ref({});
    const operState = ref(false);
    const replyState = ref(false);
    const tableData = ref([]);
    const tabsCount = ref({ DEBOX: 0, DFBOX: 0, SNBOX: 0, INBOX: 0 });
    const columns = ref([
        { title: '发件人/收件人',key: 'sender', width: 150, tableCustom: true, },
        { title: '主题', key: 'title', search: true, tableCustom: true, },
        { title: '时间',key: 'sendTime', width: 160, tableCustom: true, },
    ]);
    const config = ref({
        addBtnText: '发邮件',
        selection: true,
        editBtnHide: true,
        removeBtnHide: true,
        rowOperHide: true,
        editCustom: true,
    });
    const addBefore = () => {
        operState.value = false;
        selectrow.value = {};
        createEmailDrawerShow.value = true;
    };
    const editBefore = (rowData) => {
        operState.value = true;
        selectrow.value = rowData;
        createEmailDrawerShow.value = true;
    };
    const edit = (fromData, saveState) => {
        if(operState.value){
            const submitData = dataReorganization(fromData, saveState);
            editEmail({
                ...submitData
            }).then(res => {
                createEmailDrawerShow.value = false;
                ElMessage({ type: 'success', message: '保存成功' })
                getTablePages();
            });
            return
        }
        const submitData = dataReorganization(fromData, saveState);
        createEmail({
           ...submitData
        }).then(res => {
            createEmailDrawerShow.value = false;
            ElMessage({ type: 'success', message: '邮件发送成功', })
            getTablePages();
        });
    };
    const temporarySave = (fromData) => {
        let submitData = dataReorganization( fromData, 0 );
        submitData.mailStatus = 0;
        createEmail({
           ...submitData
        }).then(res => {
            ElMessage({ type: 'success', message: '邮件已保存至草稿箱', })
            getTablePages();
        });
    };
    const readItems = () => {
        if(selectedRows.value.length <= 0){
            ElMessage({ type: 'warning', message: '请至少选择一项操作项', })
            return
        }
        const emailIds = selectedRows.value.map( item => item.id );
        proxy.$modal.confirm(`是否批量阅读已选择邮件？`).then(function() {
            readEamils( emailIds ).then(response => {
                proxy.$modal.msgSuccess("操作成功");
                getTablePages();
            });
        }).catch(() => {});
    };
    const removeItems = (item) => {
        if(item && item.id){ // 单个删除
            proxy.$modal.confirm(`是否删除[ ${item.title} ]邮件吗？`).then(function() {
                removeEmails( [ item.id ] ).then(response => {
                    proxy.$modal.msgSuccess("删除成功");
                    emailDetailRef.value.handleClose();
                    getTablePages();
                });
            }).catch(() => {});
            return
        }
        if(selectedRows.value.length <= 0){
            ElMessage({ type: 'warning', message: '请至少选择一项操作项', })
            return
        }
        const emailTitles = selectedRows.value.map( item => item.asMail && item.asMail.title );
        const emailIds = selectedRows.value.map( item => item.mailId );
        proxy.$modal.confirm(`是否删除[ ${emailTitles.toString()} ]等邮件吗？`).then(function() {
            removeEmails( emailIds ).then(response => {
                proxy.$modal.msgSuccess("删除成功");
                getTablePages();
            });
        }).catch(() => {});
    };
    const recoverItems = () => {
        if(selectedRows.value.length <= 0){
            ElMessage({ type: 'warning', message: '请至少选择一项操作项', })
            return
        }
        const emailTitles = selectedRows.value.map( item => item.asMail && item.asMail.title );
        const emailIds = selectedRows.value.map( item => item.mailId );
        proxy.$modal.confirm(`是否恢复[ ${emailTitles.toString()} ]等已删除邮件？`).then(function() {
            recoverEmail( emailIds ).then(response => {
                proxy.$modal.msgSuccess("邮件已恢复");
                getTablePages();
            });
        }).catch(() => {});
    };
    const replyEmail = (emailInfo, state) => {
        operState.value = false;
        replyState.value = state; // 转发状态：false=回复  true=转发
        selectrow.value = emailInfo;
        replyEmailDrawerShow.value = true;
    };
    const handleSelectionChange = (rows) => {
        selectedRows.value = rows;
    };
    const checkDetail = (rowData) => {
        selectrow.value = rowData;
        if(activeName.value == '1'){
            editBefore(rowData);
            return
        }
        emailDetailDrawerShow.value = true;
    };
    const dataReorganization = (formData, status) => {
        if(formData.fileList && formData.fileList.length ){
            formData.fileListUrlList = formData.fileList.map( item => item.url );
        }
        const submitData = {
            id: formData.id || '',
            quoteMailId: formData.quoteMailId || '',
            title: formData.title,
            content: formData.content,
            attach: formData.fileListUrlList ? formData.fileListUrlList.toString() : '',
            mailUserList: []
        }
        if(!submitData.id) delete submitData.id
        if(formData.receiverList && formData.receiverList.length ){
            formData.receiverList.map( item => {
                const obj = { userId: item, userType: 1, mailStatus: status }
                submitData.mailUserList.push(obj);
            });
        }
        if(formData.ccList && formData.ccList.length ){
            formData.ccList.map( item => {
                const obj = { userId: item, userType: 2, mailStatus: status }
                submitData.mailUserList.push(obj);
            });
        }
        return submitData
    };
    const tabChange = (value) => {
        activeName.value = value.paneName;
        switch (activeName.value) {
            case '0': mailStatus.value = '1';userTypes.value = '1,2'; break;
            case '1': mailStatus.value = '0';userTypes.value = '0'; break;
            case '2': mailStatus.value = '1';userTypes.value = '0'; break;
            case '3': mailStatus.value = '2';userTypes.value = '0,1,2'; break;
            default: mailStatus.value = '1';userTypes.value = '1,2'; break;
        }
        pages.value.page_current = 1;
        getTablePages();
    };
    const currentChange = (current) => {
        pages.value.page_current = current;
        getTablePages();
    };
    const sizeChange = (size) => {
        pages.value.page_size = size;
        getTablePages();
    };
    const refresh = () => {
        getTablePages();
    };
    const search = (searchParam) => {
        searchParams.value = searchParam.value;
        getTablePages();
    }
    const searchReset = () => {
        searchParams.value = {};
        getTablePages();
    };
    const getTablePages = () => {
        loading.value = true;
        emailPages({
            current: pages.value.page_current,
            size: pages.value.page_size,
            mailStatus: mailStatus.value,
            userTypes: userTypes.value,
            ...searchParams.value
        }).then(res => {
            tableData.value = res.data.records;
            total.value = res.data.total;
            loading.value = false;
        });
        getTabsCount();
    };
    const getTabsCount = () => {
        tabsStatistics({}).then(res => {
            const resCount = res.data || {}
            for( const key in tabsCount.value){
                tabsCount.value[key] = resCount[key];
            }
        });
    };
    onMounted(() => {
        getTablePages();
    })
</script>
<style scoped lang="scss">
</style>